package arithmetic.LeetCode._394DecodeString;

/**
 * 394. Decode String
 *
 * @author zhangyanqi
 * @since 1.0 2018/1/6
 */
public class Solution {

    public String decodeString(String s) {
        int i = s.indexOf("[");//获得第一个[的位置
        if (i == -1) {
            return "";
        }
        int time = Integer.parseInt(s.substring(i - 1, i)); //获得重复的次数
        String lastString = s.substring(s.indexOf("[") + 1);//获得剩下的字符串 asdfasdf]....
        int close = lastString.indexOf("]");//获得剩下字符串中结束标志的的位置
        int anotherBegin = lastString.indexOf("[");//获得剩下字符串中开始标志的位置
        if (anotherBegin == -1) {//没有多的开始符号  3[abch]abc
            String substring = lastString.substring(0, close); // abch]abc
            StringBuilder sb = new StringBuilder();
            for (int a = 0; a < time; a++) {
                sb.append(substring);
            }
            sb.append(lastString.substring(close + 1, lastString.length()));
            return sb.toString();
        }
        if (close < anotherBegin) { //并列关系 还有内容 abc] vv 2[....]....
            String substring = lastString.substring(0, close); // abc
            StringBuilder sb = new StringBuilder();
            for (int a = 0; a < time; a++) {
                sb.append(substring);
            }
            if (anotherBegin - close > 2) {
                sb.append(lastString.substring(close, anotherBegin - 1)); //abcabcvv
            }
            String s1 = lastString.substring(anotherBegin - 1, lastString.length());
            return sb.toString() + decodeString(s1);
        } else {
            String substring1 = lastString.substring(0, anotherBegin - 1);
            int i1 = lastString.lastIndexOf("]");
            String substring2 = lastString.substring(anotherBegin - 1, i1);
            String substring3 = lastString.substring(i1 + 1, lastString.length());
            String result = decodeString(substring2);
            StringBuilder sb = new StringBuilder(substring1 + result);
            for (int a = 0; a < time; a++) {
                sb.append(sb);
            }
            sb.append(substring3);
            return sb.toString();
        }
    }


    public static void main(String[] args) {
        String a = "2[ab3[cd]]4[xy]";
        String s = new Solution().decodeString(a);
        System.out.println(s);
    }

}
